package com.group3.controller.Validated;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.regex.Pattern;

/**
 * MyEmail
 *
 * @author HY
 * 2021/07/17 14:57
 **/

@Constraint(validatedBy = MyEmail.MyEmailValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyEmail {

    String message() default "邮箱格式不合法";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class MyEmailValidator implements ConstraintValidator<MyEmail, String> {

        private Pattern pattern = Pattern.compile("\\s*?(.+)@(.+?)\\s*$");

        @Override
        public void initialize(MyEmail myEmail) {
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value != null) {
                return pattern.matcher(value).matches();
//                context.disableDefaultConstraintViolation();
//                context
//                        .buildConstraintViolationWithTemplate("User " + value + "already exists!")
//                        .addConstraintViolation();
            }
            return true;
        }
    }

}
